param(
  [string]$ConfigPath = (Join-Path (Split-Path $PSScriptRoot -Parent) "Conf\DNSService.conf"),
  [string]$CommandsFile,
  [switch]$StartService = $true,
  [int]$StartupWaitMs = 1500
)

$ErrorActionPreference = "Stop"

$repoRoot = Split-Path $PSScriptRoot -Parent

if (-not (Test-Path $ConfigPath)) {
  Write-Error "配置文件不存在: $ConfigPath"
}

# 加载命令列表（支持从文件或使用默认命令集）
$cmds = @()
if ($CommandsFile -and (Test-Path $CommandsFile)) {
  $cmds = Get-Content -Path $CommandsFile | Where-Object { $_ -and $_.Trim() -notmatch '^[\s#]'}
} else {
  $cmds = @(
    "status",
    "list-upstream",
    "ADD_RECORD script-demo.com 1.2.3.4",
    "LIST_RECORDS",
    "REMOVERECORD script-demo.com",
    "ADDPTRRECORD 1.2.3.4 host.script",
    "REMOVEPTRRECORD 1.2.3.4",
    "exit"
  )
}

$svcProc = $null
try {
  if ($StartService) {
    Write-Host "启动服务..." -ForegroundColor Cyan
    $svcProc = Start-Process -FilePath "dotnet" -ArgumentList "run --project `"$repoRoot\LocalDnsService.csproj`"" -WorkingDirectory $repoRoot -PassThru -NoNewWindow
    Start-Sleep -Milliseconds $StartupWaitMs
  }
}
finally {
  if ($svcProc) {
    Write-Host "停止服务..." -ForegroundColor Cyan
    try { $svcProc.Kill() } catch { }
  }
}